package net.alche.fa.core.doing;
import net.alche.fa.core.model.Logic;
import net.alche.fa.core.model.FaValue;
import net.alche.fa.core.CodeLevel;
import net.alche.fa.core.SageStone;
import net.alche.fa.core.FaException;
import net.alche.fa.core.parse.FaKeyWord;

//
// var
//
@FaAnnoDoing
public class VarDo extends AbstractDoing {

  @Override
  public boolean matched(String what, Logic g) {
    return what != null && what.startsWith("var-");
  }

  @Override
  public FaValue doing(Logic g, CodeLevel lvl, SageStone st) throws FaException {
    FaValue fav = new FaValue();
    fillFaValueType(fav, g.getWhat());
    fav.setNull(true);
    st.putVar(g.getObj(), fav);
    return fav;
  }

  public void fillFaValueType(FaValue fav, String typeWhat) {
    String type = typeWhat.substring(4, typeWhat.length());
    if (type.endsWith("[]")) {
      fav.setType(FaValue._ARR);
    }
    else if ( isMap(type)) {
      fav.setType(FaValue._MAP);
    }
    else if ( isList(type)) {
      fav.setType(FaValue._LIST);
    }
    else if ( FaKeyWord.isBaseDataType(type)) {
      fav.setType(FaValue.getChar(type));
    }
    else if ( super.plat.isSageName(type)) {
      fav.setType(FaValue._SAGE);
    }
    else {
      fav.setType(FaValue._OBJECT);
    }
    fav.setObjType(type);
  }

  // 判断是Map
  static boolean isMap(String type) {
    if (type.startsWith("Map")|| type.startsWith("HashMap")|| type.startsWith("LinkedHashMap")) {
      return true;
    }
    return false;
  }

  // 判断是List
  static boolean isList(String type) {
    if (type.startsWith("List")|| type.startsWith("ArrayList")|| type.startsWith("LinkedList")) {
      return true;
    }
    return false;
  }
}